<template>
	<a-upload
		v-model:file-list="fileList"
		class="upload-list-inline"
		:custom-request="customRequestAliyun"
		@change="handleChange"
		:maxCount="limit"
	>
		<a-button>
			<upload-outlined></upload-outlined>
			文件上传
		</a-button>
	</a-upload>
</template>

<script setup>
	import fileApi from '@/api/dev/fileApi'
	import { ref } from 'vue'

	const fileList = ref([])

	const flieName = ref([])

	const props = defineProps({
		limit: Number
	})

	//删除
	const handleChange = (info) => {
		//console.log(fileList.value)
	}

	//地址路径解析
	const getFileName = (path) => {
		if (path.lastIndexOf('\\') >= 0) {
			let reg = new RegExp('\\\\', 'g')
			path = path.replace(reg, '/')
		}
		//通过数据库获取文件名称
		//var fileId = path.substring(path.lastIndexOf('/') + 1).split('.')[0]
		//getFileDetail(fileId)
		return path.substring(path.lastIndexOf('/') + 1)
	}
	// 获取文件名称
	const getFileDetail = async (fileId) => {
		const param = {
			id: fileId
		}
		fileApi.fileDetail(param).then((data) => {
			console.log(data.name)
			flieName.value.push(data.name)
		})
	}

	//生成随机id
	const uidGenerator = () => {
		return '-' + parseInt(Math.random() * 10000 + 1, 10)
	}

	//构造通用附件对象
	const initFileInfo = (url) => {
		const name = getFileName(url)
		let itemValue = {
			uid: uidGenerator(),
			name: name,
			status: 'done',
			response: url,
			url: url
		}
		return itemValue
	}

	//回填上传数据列表
	const initFileList = (record) => {
		let paths = record
		if (!paths || paths.length === 0) {
			return 0
		}
		paths.split(',').forEach((item) => {
			let itemValue = initFileInfo(item)
			fileList.value.push(itemValue)
		})
	}

	// 上传阿里云文件
	const customRequestAliyun = (data) => {
		const fileData = new FormData()
		fileData.append('file', data.file)
		fileApi
			.fileUploadAliyunReturnUrl(fileData)
			.then((file) => {
				data.onSuccess(file)
			})
			.finally(() => {
				//uploadLoading.value = false
			})
	}
	//组装路径
	const buildUrl = () => {
		if (fileList.value) {
			return fileList.value
				.map((x) => {
					return x.response
				})
				.join(',')
		} else {
			return ''
		}
	}

	// 抛出这个获取文件列表的方法
	defineExpose({
		initFileList,
		buildUrl
	})
</script>
